package com.szpxt.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

import com.szpxt.model.Privilege;
import com.szpxt.model.Role;

@Component
public class RoleService extends HibernateDaoSupport {

	private PrivilegeService privilegeService;
	
	public List<Role> getAll() {
		DetachedCriteria criteria = DetachedCriteria.forClass(Role.class);
		return (List<Role>)getHibernateTemplate().findByCriteria(criteria);
	}
	
	public Role saveOrUpdate(Map map) {
		Role role = new Role();
		
		String id = ((String[])map.get("id"))[0];
		if(!StringUtils.isBlank(id)) {			//修改情况
			role = get(Long.parseLong(id));
		}
		
		String name = ((String[])map.get("name"))[0];
		List<Privilege> listPrivilege = new ArrayList<Privilege>();
		
		List<Privilege> allPrivilege = privilegeService.getAll();
		for(Privilege element: allPrivilege) {
			if(map.containsKey(element.getKey())) {
				listPrivilege.add(element);
			}
		}
		
		
		role.setName(name);
		role.setListPrivilege(listPrivilege);
		
		getHibernateTemplate().saveOrUpdate(role);
		
		return role;
	}
	
	public Role get(long id) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Role.class);
		criteria.add(Restrictions.eq("id", id));
		
		return (Role)getHibernateTemplate().findByCriteria(criteria).get(0);
	}
	
	public void delete(long id) {
		Role role = get(id);
		getHibernateTemplate().delete(role);
	}
	
	public void saveOrUpdate(Role role) {
		getHibernateTemplate().saveOrUpdate(role);
	}

	//获取和设置方法
	public PrivilegeService getPrivilegeService() {
		return privilegeService;
	}

	public void setPrivilegeService(PrivilegeService privilegeService) {
		this.privilegeService = privilegeService;
	}
	
}
